<?php
/**
 * Created by PhpStorm.
 * User: DaveTang
 * Date: 2020/3/3
 * Time: 15:56
 * 用户信息缓存组件
 */

namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\Cache\Cache;

class InStockCacheComponent extends Component
{

    public $_cache_config = 'goods_instocks';
    public function initialize(array $config)
    {
        parent::initialize($config);
    }

    /**
     * 获取缓存
     */
    public function getVal($good_id)
    {
        $data = Cache::read('in_'.$good_id, $this->_cache_config);
        return empty($data) ? $this->createCache($good_id) : $data;
    }

    /**
     * 创建缓存
     */
    public function createCache($good_id)
    {
        $controller = $this->_registry->getController();
        $controller->loadModel('GoodsInstocks');
        $data = $controller->GoodsInstocks->find()
            ->select(['num'=>'sum(num)'])
            ->where(['good_id' => $good_id])
            ->first();
        $cache = empty($data) ? 0 : $data['num'];
        Cache::write('in_'.$good_id, $cache, $this->_cache_config);
        return $cache;
    }

    /**
     * 删除缓存
     */
    public function deleteCache($good_id)
    {
        Cache::delete('in_'.$good_id, $this->_cache_config);
        return true;
    }

}